// pages/address/list/index.js
import { reqAddressList, reqDelAddress } from '../../../api/address'
import instance from '@/utils/http'
import { swiperCellBehavior } from '@/behaviors/swiperCell'
const app = getApp() // 获取应用实例

Page({
  behaviors: [swiperCellBehavior],
  // 页面的初始数据
  data: {
    addressList: []
  },

  // 去编辑页面
  toEdit(event) {
    const { id } = event.currentTarget.dataset

    wx.navigateTo({
      url: `/modules/settingModule/pages/address/add/index?id=${id}`
    })
  },

  // 获取收货地址列表：
  async getAddressList() {
    const { data: addressList } = await reqAddressList()
    // const res = await reqAddressList()
// console.log(res);

    this.setData({ addressList })
  },

  // 当前页面
  onShow() {
    this.getAddressList()
  },
  // 删除地址：
  async delAddress(event) {
    // 解构传递的 id:
    const { id } = event.currentTarget.dataset

    const modalRes = await wx.modal({
      content: "您确认删除收货地址吗？"
    })

    // 如果确认删除：则调用 删除地址（reqDelAddress） 接口api
    // 同时需要给出 删除成功 提示,并重新获取地址列表
    if (modalRes) {
      await reqDelAddress(id)
      wx.toast({ title: '收货地址删除成功' })
      this.getAddressList()
    }
  },

  SwiperCellClick(event){
    console.log(event);
  },

  // onLoad: 在页面加载时触发
  onLoad(options) {
    this.flag = options.flag
  },

  changeAddress(event) {
    if (this.flag !== '1') return
    const addressId = event.currentTarget.dataset.id
    // console.log(addressId);
    const selectAddress = this.data.addressList.find((item) => item.id === addressId)
    if (selectAddress) {
      app.globalData.address = selectAddress
      wx.navigateBack()
    }
  },


})
